/**
 * 工具类
 * 使用方法： this.$utils
 */
import stroe from '@/store'
import router from '@/router'
/**
 * 跳转方法
 * @param {*} href 路径 (内部路由跳转, http跳转, 后退)
 * @param {*} is 是否新开选项卡 (后退不支持)
 */
function jump (href, is = false) {
  const _this = router.app
  // 空 -1 或者 @click="jump" 这样 href 会默认传原生 event 类型为 object
  if (!href || typeof href === 'object' || href === -1) {
    _this.$router.go(-1)
    return false
  }
  if (is) {
    let aHref = ''
    if (href.indexOf('https://') === 0 || href.indexOf('http://') === 0) {
      aHref = href
    } else {
      aHref = window.location.protocol + '//' + window.location.host + '/' + require('../../package.json').name + href
    }
    const a = document.createElement('a')
    a.href = aHref
    a.target = '_blank'
    a.click()
  } else {
    if (href.indexOf('https://') === 0 || href.indexOf('http://') === 0) {
      location.href = href
    } else {
      if (_this.$route.fullPath !== href) _this.$router.push(href)
    }
  }
}

/**
 * js 适配方法
 * @param {*} callback1 手机 回调
 * @param {*} callback2 平板 回调
 * @param {*} callback3 PC 回调
 */
function adap (callback1, callback2, callback3) {
  if (stroe.state.width <= 1280) callback1(stroe.state.width)
  else if (stroe.state.width <= 1600) callback2(stroe.state.width)
  else callback3(stroe.state.width)
}

/**
 * 复制到剪切板
 * @param {*} text 文字
 * @param {*} callback 回调
 */
function copyText (text, callback) {
  const input = document.createElement('textarea')
  input.setAttribute('readonly', 'readonly') // 防止手机上弹出软键盘
  input.innerHTML = text
  document.body.appendChild(input)
  input.select()
  document.execCommand('copy', 'false', null)
  document.body.removeChild(input)
  if (callback) {
    callback(text)
  }
}

/**
 * 上传
 * @param {Object} attrs 属性
 * - accept 限制类型 如 '.doc,.docx,.xlsx,.xls,.pdf,.png,.jpg'
 * - multiple 是否支持多选 Boolean
 *
 */
function upload (attrs = {}) {
  const input = document.createElement('input')
  input.type = 'file'
  Object.keys(attrs).forEach(key => (input[key] = attrs[key]))
  input.click()
  return new Promise(resolve => {
    input.addEventListener('change', event => {
      resolve(event.path[0].files)
    })
  })
}

/**
 * 统计图解析数据
 * @param {Array} data
 * [{x: '08:00', y: 5, type: '出'}, {x: '08:00', y: 8, type: '入'}, {x: '08:10', y: 1, type: '出'}, {x: '08:10', y: 2, type: '入'}]
 *
 * @return {Object}
 * {
 *  legend: ['出', '入'],
 *  x: ['08:00', '08:10']
 *  y: [[5, 1], [8, 2]]
 * }
 */
function parseChartData (data) {
  const result = {}
  result.legend = distinct(data.map(item => item.type))
  result.x = distinct(data.map(item => item.x))

  result.y = result.legend.map(item => result.x.map(it => {
    const findObject = data.find(fItem => fItem.type === item && fItem.x === it)
    let value = 0
    if (findObject && findObject.y) {
      value = findObject.y
    }
    return value
  }))
  return result
}

/**
 * 数组去重
 * @param {Array} array
 */
function distinct (array) {
  return Array.from(new Set(array))
}

function deepClone (source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * 随机生成不重复 ID
 */
const uuid = () => (Math.random() * 10000000).toString(16).substr(0, 4) + '-' + (new Date()).getTime() + '-' + Math.random().toString().substr(2, 5)

/**
 * 并发 api 集合
 * @param {*} apiArr
 * @param {*} callback
 * this.$utils.sendApis([this.$api.test.list(), this.$api.test.options()], response => {
      console.log(response)
   })
 */
const sendApis = (apiArr, callback) => {
  Promise.all(apiArr).then(values => {
    if (callback) { callback(values) }
  }).catch(error => {
    console.error('sendApis 错误', error)
  })
}

export default {
  jump,
  adap,
  copyText,
  upload,
  parseChartData,
  distinct,
  uuid,
  deepClone,
  sendApis
}
